package jh.com.jhappbf.weight.query;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;

import com.ab.activity.AbActivity;
import com.ab.fragment.AbDialogFragment.AbDialogOnLoadListener;
import com.ab.fragment.AbLoadDialogFragment;
import com.ab.util.AbDialogUtil;
import com.ab.view.titlebar.AbTitleBar;
import com.android.volley.Request.Priority;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;

import jh.com.jhappbf.R;
import jh.com.jhappbf.database.SQLiteDataBaseUtil;
import jh.com.jhappbf.httputils.VolleyCallWebService;
import jh.com.jhappbf.httputils.VolleySingleton;
import jh.com.jhappbf.utils.JsonHelper;


public class QuerySettingField extends AbActivity {
    private AbLoadDialogFragment mDialogFragment = null;
    private ListView mListView;
    private List<JSONObject> mData;
    private myBaseAdapter mAdapter;
    private List<String> mSelectItem;
    private Context mAppContext;
    private  View mContentView;
    private View mErrorView;
    private Button mTryAgin;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContentView = getLayoutInflater().inflate(R.layout.query_weight_setting_fileds, null);
        mErrorView = getLayoutInflater().inflate(R.layout.net_error_activity, null);
        setAbContentView(mContentView);
        AbTitleBar mAbTitleBar = this.getTitleBar();
        mAbTitleBar.setTitleText("字段设置");
        mAbTitleBar.setLogo(R.drawable.button_selector_back);
        mAbTitleBar.setTitleBarBackground(R.drawable.top_bg);
        mAbTitleBar.setTitleTextMargin(10, 0, 0, 0);
        mAbTitleBar.setLogoLine(R.drawable.line);
        initView();
    }

    /**
     * 初始化
     */
    private void initView() {
        mListView = (ListView) mContentView.findViewById(R.id.query_setting_fileds_listView);
        mTryAgin = (Button) mErrorView.findViewById(R.id.network_error_btn);

        mSelectItem = new ArrayList<String>();
        mAppContext = getApplicationContext();
        mData = new ArrayList<JSONObject>();
        mAdapter = new myBaseAdapter();
        mListView.setAdapter(mAdapter);
        getSetting();
        LoadFirst();

        mTryAgin.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                setAbContentView(mContentView);
                LoadFirst();
            }
        });

        mListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                CheckBox chk = (CheckBox) view
                        .findViewById(R.id.query_filed_setting_chk);
                TextView txt = (TextView) view
                        .findViewById(R.id.query_filed_setting_txt);
                String name = (String) txt.getText();
                String filed = (String) txt.getTag();
                if (chk.isChecked()) {
                    chk.setChecked(false);
                    if (isContain(filed)) {
                        remove(filed);
                        removeSetting(filed, name);
                    }
                } else {
                    chk.setChecked(true);
                    if (!isContain(filed)) {
                        mSelectItem.add(filed);
                        saveSetting(filed, name);
                    }
                }
            }
        });
    }

    /**
     * 第一次加载
     */
    private void LoadFirst() {
        mDialogFragment = AbDialogUtil.showLoadDialog(this, R.drawable.ic_load,
                "查询中,请稍等...");
        mDialogFragment.setCancelable(false);
        mDialogFragment.setAbDialogOnLoadListener(new AbDialogOnLoadListener() {

            @Override
            public void onLoad() {
                getData();
            }
        });
    }

    /**
     * 获取数据
     */
    private void getData() {
        String methodName = "getQueryFileds";
        ArrayList<String> param = new ArrayList<String>();
        ArrayList<String> value = new ArrayList<String>();

        Listener<String> listener = new Listener<String>() {
            @Override
            public void onResponse(String response) {
                AbDialogUtil.removeDialog(QuerySettingField.this);
                List<JSONObject> data = JsonHelper.getJsonObjects(response);
                if (data != null) {
                    mData = data;
                    mAdapter.notifyDataSetChanged();
                }
            }
        };

        ErrorListener errorListener = new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                AbDialogUtil.removeDialog(QuerySettingField.this);
                setAbContentView(mErrorView);
            }
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(getApplicationContext()).addRequest(
                webService);
    }

    /**
     * 获取保存的设置
     */
    private void getSetting() {
        Cursor cursor = null;
        try {
            SQLiteDatabase db = SQLiteDataBaseUtil.getDatabase(mAppContext);
            cursor = db.query("saverFileds", new String[] { "field" }, null,
                    null, null, null, "  id asc ");
            if (cursor != null) {
                String filed = "";
                while (cursor.moveToNext()) {
                    filed = cursor.getString(0);
                    if (filed.length() > 0) {
                        mSelectItem.add(filed);
                    }
                }
            }
        } catch (Exception e) {
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    /**
     * 保存到本地
     */
    private void saveSetting(String filed, String alias) {
        SQLiteDatabase db = SQLiteDataBaseUtil.getDatabase(mAppContext);
        ContentValues values = new ContentValues();
        values.put("field", filed);
        values.put("alias", alias);
        long len = db.insert("saverFileds", null, values);
        if (len > 0) {
            len = 0;
        }
    }

    /**
     * 从数据库中删除
     */
    private void removeSetting(String filed, String alias) {
        SQLiteDatabase db = SQLiteDataBaseUtil.getDatabase(mAppContext);
        db.delete("saverFileds", " field=? and alias=?", new String[] { filed,
                alias });
    }

    /**
     * 判断选择项中是否已经包含
     *
     * @param value
     * @return
     */
    private boolean isContain(String value) {
        Boolean b = false;
        for (String item : mSelectItem) {
            if (item.equals(value)) {
                b = true;
                break;
            }
        }
        return b;
    }

    /**
     * 删除已选的项
     *
     * @param value
     */
    private void remove(String value) {
        Object temp = null;
        for (String item : mSelectItem) {
            if (item.equals(value)) {
                temp = item;
                break;
            }
        }
        if (temp != null) {
            mSelectItem.remove(temp);
        }
    }

    class myBaseAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return mData.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Viewhoder viewHolder = null;
            if (convertView == null) {
                viewHolder = new Viewhoder();
                LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(
                        R.layout.query_weight_setting_fileds_list_item, null);
                viewHolder.mTxt = (TextView) convertView
                        .findViewById(R.id.query_filed_setting_txt);
                viewHolder.mChk = (CheckBox) convertView
                        .findViewById(R.id.query_filed_setting_chk);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (Viewhoder) convertView.getTag();
            }
            JSONObject object = mData.get(position);
            if (object != null) {
                try {
                    String key = object.keys().next().toString();
                    String name = object.getString(key);
                    viewHolder.mTxt.setText(name);
                    viewHolder.mTxt.setTag(key);
                    if (isContain(key)) {
                        viewHolder.mChk.setChecked(true);
                    } else {
                        viewHolder.mChk.setChecked(false);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            return convertView;
        }

        class Viewhoder {
            public TextView mTxt;
            public CheckBox mChk;
        }
    }
}
